<?php
apf_require_controller("Abstract");
apf_require_class('Tools_Uploader');

class Portal_Home_UploadImgController extends AbstractController {

    public function handle_request() {

        $params = $this->request->get_parameters();
        $session_user = $this->get_user_info();
        $user_code = $session_user['code'];
        $upDir = Const_Img::PATH_BASE.Const_Img::PATH_UPLOAD.$user_code;

        if(isset($params['code'])){## 1 删除
            $old_img_name = end(explode('/',$params['old_img']));
            //删除原图
            $this->_del_old_img($upDir.'/'.$old_img_name);

            exit(0);
        }else if(isset($params['img'])){## 2 进行裁剪

            $old_img_name = end(explode('/',$params['img']));
            //删除默认裁剪图
            $this->_del_imgs_except($upDir,$old_img_name);
            //裁剪
            $new_img = $this->_clipping_img_and_save($params,$upDir,$user_code,$old_img_name);
            //删除原图
            $this->_del_old_img($upDir.'/'.$old_img_name);

            $resutl= array();
            if($new_img){
                $resutl['url'] = $new_img;
                $resutl['code'] = 1;
            }else{
                $resutl['msg'] = 'error';
                $resutl['code'] = 0;
            }
            echo json_encode($resutl);
            exit(0);
        }else{## 3 首次上传
            $resutl = array();
            $resutl['code'] = 0;
            if($_FILES[Const_Img::INPUT_FILE_NAME]['tmp_name']) {
                ## 1 上传新文件
                $uploader = new Tools_Uploader(Const_Img::INPUT_FILE_NAME);
                $uploader->setValidExt(array(
                        '.jpg',
                        '.png',
                        '.jpeg',
                        '.gif'
                ));
                $uploader->setUpDir($upDir);

                if($uploader->upload()) {
                    $img_name = $uploader->getFileName();
                    $resutl['height'] = $this->_get_img_height($upDir.'/'.$img_name);
                    $resutl['url'] = Portal_Urls::build_user_pic_path($user_code,$img_name);
                    $resutl['code'] = 1;
                }else{
                    $resutl['msg'] = $uploader->getErrorMsg();
                }
            }else{
                $resutl['msg'] = '上传失败';
            }
            echo json_encode($resutl);exit(0);
        }
    }
    /**
     * 图片裁剪
     */
    private function _clipping_img_and_save($params,$upDir,$user_code,$old_img_name){
        $height = $this->_get_img_height($upDir.'/'.$old_img_name);
        //截取成标准图
        $this->_clipping_img(array(),$upDir,$old_img_name,Const_Img::PIC_ORIGINAL_WIDTH,$height,Const_Img::PIC_ORIGINAL);
        //截取小图
        $this->_clipping_img($params,$upDir,Const_Img::PIC_ORIGINAL,Const_Img::PIC_SMALL_WIDTH,Const_Img::PIC_SMALL_HEIGHT,Const_Img::PIC_SMALL);
        //截取大图
        $this->_clipping_img($params,$upDir,Const_Img::PIC_ORIGINAL,Const_Img::PIC_BIG_WIDTH,Const_Img::PIC_BIG_HEIGHT,Const_Img::PIC_BIG);

        return Portal_Urls::build_user_pic_path($user_code,Const_Img::PIC_BIG);
    }
    /**
     * 定高320px
     * 变宽
     */
    private function _get_img_height($path){
        list($w, $h, $type, $attr) = getimagesize($path);
        return Const_Img::PIC_ORIGINAL_WIDTH*$h/$w;
    }
    /**
     * 图片裁剪
     */
    private function _clipping_img($params,$upDir,$old_img_name,$targ_w,$targ_h,$output_filename){
        $end_ext = strtolower(strrchr($old_img_name, '.'));

        //截取参数
        $x = intval($params['x1']);
        //$x2 = intval($params['x2']);
        $y = intval($params['y1']);
        //$y2 = intval($params['y2']);
        $w  = intval($params['w']);
        $h  = intval($params['h']);
        if(!$w && !$h){
            list($w, $h, $type, $attr) = getimagesize($upDir.'/'.$old_img_name);
        }
        //画质
        $jpeg_quality = 100;
        //源文件
        $src = $upDir.'/'.$old_img_name;
        //获取源文件
        $img_r = '';
        if($end_ext == '.jpg' || $end_ext == '.jpeg'){
            $img_r = imagecreatefromjpeg($src);
        }elseif($end_ext == '.png'){
            $img_r = imagecreatefrompng($src);
        }elseif($end_ext == '.bmp'){
            //$img_r = imagecreatefrombmp($src);
        }elseif($end_ext == '.gif'){
            $img_r = imagecreatefromgif($src);
        }

        //创建新文件
        $dst_r = ImageCreateTrueColor( $targ_w, $targ_h );
        //截取图片
        imagecopyresampled($dst_r,$img_r,0,0,$x,$y,$targ_w,$targ_h,$w,$h);
        //保存图片
        imagejpeg($dst_r, $upDir.'/'.$output_filename, $jpeg_quality);
    }
    /**
     * 再次上传 先删除
     * @param unknown_type $dir
     * @return boolean
     */
    private function _del_imgs_except($dir,$except_img = ".") {
        //先删除目录下的文件：
        $dh=opendir($dir);
        while ($file=readdir($dh)) {
            if($file != "." && $file != ".." && $file != $except_img) {
                $fullpath=$dir."/".$file;
                if(is_file($fullpath)) {
                    unlink($fullpath);
                }
            }
        }
        closedir($dh);
    }
    /**
     * 删除img
     * @param unknown_type $fullpath
     */
    private function _del_old_img($fullpath){
        if(is_file($fullpath)) {
            unlink($fullpath);
        }
    }
}